<?php
/**
 * Created by PhpStorm.
 * User: win10
 * Date: 2017/12/11
 * Time: 15:36
 */

namespace common\services\tracking;

use Yii;
// use common\services\RedisService;
use common\models\kaoguobao\RequestLog;
use common\models\kaoguobao\Hour;

class EventService {

    /**
     * 产品点击请求，只需要传递产品的本身key就行了
     * @param string $key
     * @return int|mixed|void
     */
    public static function clickEventTracking($key = 'kgb')
    {
        if(empty(RequestLog::$key[$key])){
            return;
        }
        $type = RequestLog::$type[$key];

        $timeOld = date("Y-m-d",strtotime("-1 day"));       // 获取前一天的时间，历史数据使用
        $timeNew = date('Y-m-d');                           // 获取今天时间
        $goodsClickDataNew = RequestLog::find()
                        ->where(['date' => $timeNew])
                        ->andWhere(['key' => $key])
                        ->limit(1)
                        ->one();
        // 判断今天的计数是否产生，否则就新增
        if(empty($goodsClickDataNew)){
            // 这里查询前一天数据，每天查一次，减少数据库压力
            $goodsClickDataOld = RequestLog::find()
                ->where(['<', 'date' , $timeNew])
                ->andWhere(['key' => $key])
                ->orderBy('id desc')
                ->limit(1)
                ->one();
            // 如果老数据都是空，那就默认值给0
            $ClickRequestOld = 0;
            if(!empty($goodsClickDataOld)){
                $ClickRequestOld                    = $goodsClickDataOld->total_click_request;
                // 查询hour表判断昨天的最大数据
                $yesterday = self::dayTiptopData($key,$type,$timeOld);
                // 赋予昨天最高值
                $goodsClickDataOld->day_tiptop     = $yesterday['day_tiptop'];
                $goodsClickDataOld->day_tiptop_num = $yesterday['day_tiptop_num'];
                $goodsClickDataOld->save();
            }
            $goodsClickDataNew                      = new RequestLog();
            $goodsClickDataNew->day_click_request   = 1;
            $goodsClickDataNew->total_click_request = $ClickRequestOld + 1;
            $goodsClickDataNew->date                = $timeNew;
            $goodsClickDataNew->type                = $type;
            $goodsClickDataNew->key                 = $key;
        }else{
            $goodsClickDataNew->day_click_request   = $goodsClickDataNew->day_click_request + 1;
            $goodsClickDataNew->total_click_request = $goodsClickDataNew->total_click_request + 1;
        }
        // 保存，这里只要不出问题就行
        if($goodsClickDataNew->save()){
            self::dayRedisClickCount($key,$type);
        }
        // 返回进入当前点击访问次数
        return $goodsClickDataNew->day_click_request;
    }


    /**
     * 计算出前一天的顶峰值
     * @param $key
     * @param $timeOld
     * @return array
     */
    public static function dayTiptopData($key,$type,$timeOld)
    {
        $data = [
            'day_tiptop'     => 0,      // 日最高时间段
            'day_tiptop_num' => 0,      // 日最高点击量
        ];
        // 昨天时间戳范围
        $startTime  = strtotime($timeOld);
        $endTime    = $startTime + 86399;
        $yesterday  = Hour::find()
                            ->select('hour,hour_click_request')
                            ->where(['between','created_at',$startTime,$endTime])
                            ->andWhere(['key' => $key])
                            ->andWhere(['type' => $type])
                            ->orderBy('hour_click_request desc')
                            ->limit(1)
                            ->asArray()
                            ->one();
        // 如果昨天的数据为空就直接返回
        if(empty($yesterday)){
            return $data;
        }
        // 保险起见，在一层判断
        if(is_array($yesterday) && $yesterday){
            $data = [
                'day_tiptop'     => substr($yesterday['hour'],-2),      // 日最高时间段
                'day_tiptop_num' => $yesterday['hour_click_request'],   // 日最高点击量
            ];
        }
        return $data;
        // $redisKey   = $key.':click:'.$timeOld;
        // $yesterday  = RedisService::getInstance()->get($redisKey);
        // // 如果昨天的数据为空就直接返回
        // if(empty($yesterday)){
        //     return $data;
        // }
        // $item = json_decode($yesterday,true);
        // // 保险起见，在一层判断
        // if(is_array($item) && $item){
        //     $data = [
        //         'day_tiptop'     => array_search(max($item),$item),     // 日最高时间段
        //         'day_tiptop_num' => max($item),                         // 日最高点击量
        //     ];
        // }
        // // 结束后删除
        // RedisService::getInstance()->delete($redisKey);
        // return $data;
    }

    /**
     * 每日高峰时间段点击统计
     * @param $key
     * @param $timeNew
     */
    public static function dayRedisClickCount($key,$type)
    {

        $now = date('Y-m-d H');//当前时段
        $hourClick = Hour::find()
                        ->where(['hour' => $now])
                        ->andWhere(['key' => $key])
                        ->andWhere(['type' => $type])
                        ->limit(1)
                        ->one();
        //判断该时段是否产生计数,没有则新增
        if($hourClick){
            $hourClick->hour_click_request  = $hourClick->hour_click_request + 1;
            $hourClick->updated_at          = time();
        }else{
            $hourClick                      = new hour();
            $hourClick->hour                = $now;
            $hourClick->hour_click_request  = 1;
            $hourClick->key                 = $key;
            $hourClick->type                = $type;
            $created_at                     = time();
        }  
        $hourClick->save();      
        return;
        // $redisKey   = $key.':click:'.$timeNew;
        // $yesterday  = RedisService::getInstance()->get($redisKey);
        // // 判断数据在不在，不在就是新增
        // if(empty($yesterday)){
        //     $data[date('H')] = 1;
        // }else{
        //     $data = json_decode($yesterday,true);
        //     if(empty($data[date('H')])){
        //         $data[date('H')] = 1;
        //     }else{
        //         $data[date('H')] += 1;
        //     }
        // }
        // // 缓存就存两天，没有我也没办法了
        // RedisService::getInstance()->set($redisKey,$data,'172800');
        return;
    }
}